package easy.二叉树的后序遍历;

import java.util.ArrayList;
import java.util.List;

public class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        preorderHelper(root, result);
        return result;
    }

    private void preorderHelper(TreeNode node, List<Integer> result) {
        if (node == null) {
            return;
        }
        // 遍历左子树
        preorderHelper(node.left, result);
        // 遍历右子树
        preorderHelper(node.right, result);
        // 访问当前节点
        result.add(node.val);
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1, null, new TreeNode(2, new TreeNode(3), null));
        TreeNode root2 = new TreeNode(1, new TreeNode(2, new TreeNode(4), new TreeNode(5,
                new TreeNode(6), new TreeNode(7))), new TreeNode(3, null, new TreeNode(8,
                new TreeNode(9), null)));
        Solution solution = new Solution();
        System.out.println(solution.postorderTraversal(root).toString());
        System.out.println(solution.postorderTraversal(root2).toString());
    }
}
